package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.SHOP_GEO_KEY;


@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /** 线程池 */
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);;

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要根据坐标查询
        if (x == null || y == null){
            // 不需要坐标查询，按数据库查询
            Page<Shop> page = this.query().eq("type_id", typeId)
                                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }

        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.查询 redis、按照距离排序、分页。结果：shopId、distance
        String key = SHOP_GEO_KEY + typeId;
        // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        // 此处 limit 一直都是从0开始截取到 end
                        RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().limit(end));
        // 4.解析出 id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }

    @Override
    /**
     * 缓存穿透 缓存 null 值
     * */
    public Result queryById(Long id) {
        Shop shop = queryWithMutex(id);
        if (shop == null){
            return Result.fail("店铺不存在!");
        }
        return Result.ok(shop);
    }

    /**
     * 缓存击穿 逻辑过期
     * */
    public Shop queryLogicExpire(Long id){
        String key = RedisConstants.CACHE_SHOP_KEY + id;

        // 从 redis 缓存获取
        String jsonRedisData = stringRedisTemplate.opsForValue().get(key);

        // 判断缓存是否命中
        if (StrUtil.isBlank(jsonRedisData)){
            // 未命中
            return null;
        }

        // 命中
        RedisData redisData = JSONUtil.toBean(jsonRedisData, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        // 判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            // 未过期
            return shop;
        }

        // 过期,进行缓存重建
        // 判断是否获取锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock){
            // 开启线程重建缓存
            CACHE_REBUILD_EXECUTOR.submit( () -> {
                try {
                    this.saveShopRedis(id, 20L);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    unlock(lockKey);
                }
            });
        }

        return shop;
    }

    /**
     * 缓存击穿 互斥锁
     * 缓存穿透 缓存 null 值
     * */
    public Shop queryWithMutex(Long id) {
        // 从 redis 查询商铺缓存
        String shopJSON = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        // 判断是否存在
        if (StrUtil.isNotBlank(shopJSON)){
            return JSONUtil.toBean(shopJSON, Shop.class);
        }
        // 判断是否命中
        if (shopJSON != null){
            // 此时为“”，即发生缓存穿透
            return null;
        }

        // 数据库查询
        // 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            if (!isLock){
                // 获取锁失败，休眠后重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            // 成功获取互斥锁,查询数据库
            shop = this.getById(id);

            // 数据库不存在该数据
            if (shop == null){
                // 为了避免缓存穿透，缓存 null 值
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id,
                        "", RedisConstants.CACHE_NULL_TTL,
                        TimeUnit.MINUTES);
                return null;
            }

            // 放入缓存
            String str = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id,
                    str, RedisConstants.CACHE_SHOP_TTL,
                    TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            // 释放锁
            unlock(lockKey);
        }

        return shop;
    }

    /**
     * 互斥锁  获取锁
     * 使用 redis 的 setnx 命令达到加锁的效果
     * */
    private boolean tryLock(String key){
        // 使用redis中的SETNX key value digital timeUnit来模拟获得锁
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1",
                                                RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
        // 不能直接返回，有可能null的时候自动装箱，然后就变成false
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 互斥锁  释放锁
     * */
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    /**
     * 缓存更新
     * 先更新数据库,后删除缓存
     * */
    public Result saveShop(Shop shop) {
        Long id = shop.getId();
        if (id == null){
            return Result.fail("店铺 id 不能为空!");
        }
        // 更新数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok(shop.getId());
    }

    /**
     * 缓存击穿-逻辑过期-缓存预热，将热点 key 提前放入 redis
     * */
    public void saveShopRedis(Long id, Long expireSecond) {
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSecond));
        redisData.setData(this.getById(id));
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,
                                                JSONUtil.toJsonStr(redisData));
    }

}
